﻿#ifndef JSONCONVERT_H
#define JSONCONVERT_H

#include <QJsonValue>
#include <QVariant>

namespace Custom
{
    struct Price
    {
        double price;
    };

    template<class T>
    inline T fromJson(const QJsonValue &value)
    {
        switch (value.type())
        {
            case QJsonValue::Bool:
                return QVariant(value.toBool()).value<T>();

            case QJsonValue::Double:
                return QVariant(value.toDouble()).value<T>();

            case QJsonValue::String:
                return QVariant(value.toString()).value<T>();

            default:
                return QVariant(value).value<T>();
        }
    }

    template<class T, class W>
    inline T fromJson(const QJsonValue &value)
    {
        if (value.isNull())
        {
            return QVariant(value).value<T>();
        }
        else
        {
            return QVariant(QVariant(value).value<W>()).value<T>();
        }
    }

    template<>
    inline QString fromJson<QString, Price>(const QJsonValue &value)
    {
        if (value.isNull())
        {
            return QString();
        }
        else
        {
            static const QString sc_strFormat = "%1";
            return sc_strFormat.arg(fromJson<double>(value), -2, 'f', 2, QChar('0'));
        }
    }
}

#endif // JSONCONVERT_H
